package cn.tedu.stx_admin.security;

import cn.tedu.stx_admin.dao.persist.repository.IAdminRepository;
import cn.tedu.stx_admin.pojo.vo.AdminLoginInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 实现UserDetailsService的类会在用户登录时自动加载
 */
@Slf4j
@Service
public class UserDetailsServerImpl implements UserDetailsService {
    @Autowired
    private IAdminRepository adminRepository;

    @Override
    public UserDetails loadUserByUsername(String adminName) throws UsernameNotFoundException {
        log.info("loadUserByUsername："+adminName);
        AdminLoginInfoVO loginInfoVO = adminRepository.getLoginVOByAdminName(adminName);
        if (loginInfoVO==null){
            return null;
        }

        List<GrantedAuthority> authorities = new ArrayList<>();
        for (String auth: loginInfoVO.getPermissions()){
            GrantedAuthority authority =new SimpleGrantedAuthority(auth);
            authorities.add(authority);
        }

        CustomUserDetails userDetails = new CustomUserDetails(
                loginInfoVO.getAdminName(),
                loginInfoVO.getPassword(),
                authorities,
                loginInfoVO.getId(),
                loginInfoVO.getImgUrl());

        log.debug("返回userDetails类型 : {}",userDetails);
        return userDetails;
    }
}
